﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TsCore;
using System.IO;

namespace TsWeb.Followers
{
    public partial class ViewMatches : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindMatches();
                BindSports();
            }
        }

        private void BindMatches()
        {
            MatchesGrid.DataSource = TsSystem.Instance.GetAllMatchesWithTeams();
            MatchesGrid.DataBind();
        }


        private void BindSports()
        {
            List<Sport> sportList = TsSystem.Instance.GetAllSports();
            ComboBoxSports.DataSource = sportList;
            ComboBoxSports.DataBind();
            if (sportList.Count > 0)
                ComboBoxSports_SelectedIndexChanged(null, null);
        }

        
        protected void MatchesGrid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = MatchesGrid.Rows[index];
            int MatchKey = Convert.ToInt32(row.Cells[0].Text);

            if (e.CommandName == "AddMediaCommand")
            {

                Match match = TsSystem.Instance.GetMatch(MatchKey);
                Session["Match"] = match;
                
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "$('#myModal').modal('show');", true);             
            }
        }

        protected void UpdateMatchButton_Click(object sender, EventArgs e)
        {
            Match match = (Match)Session["Match"];
            TsSystem.Instance.updateMatch(match);
        }

        protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
            if (AsyncFileUpload1.HasFile)
            {
                int is_valid = 0;

                is_valid = chkValidExtension(Path.GetExtension(e.FileName));
                string filepath="#";
                string newImageUrl ="#";
                switch (is_valid)
                {
                    case 1: //Es una foto
                        {
                            filepath = MapPath("~/Images/") + System.IO.Path.GetFileName(e.FileName);
                            newImageUrl = "~/Images/" + e.FileName;
                            try
                            {
                                AsyncFileUpload1.SaveAs(filepath);
                            }
                            catch (Exception ex)
                            {
                                //TODO: Loggear
                            }
                          
                        }
                        break;
                    case 2:
                        {
                            filepath = MapPath("~/Videos/") + System.IO.Path.GetFileName(e.FileName);
                            newImageUrl = "~/Videos/" + e.FileName;
                            try
                            {
                                AsyncFileUpload1.SaveAs(filepath);
                            }
                            catch (Exception ex)
                            {
                                //TODO: Loggear
                            }
                        }
                        break;
                }
                if (is_valid > 0)
                {
                    Match match = (Match)Session["Match"];
                    Media newMedia = new Media();
                    newMedia.Medias = newImageUrl;
                    match.MediaList.Add(newMedia);
                    Session["Match"] = match;
                }                
            }
        }
                
        public int chkValidExtension(string ext)
        {
                string[] PosterAllowedExtensions = new string[] { ".gif", ".jpeg", ".jpg", ".png",".bmp", };
                for (int i = 0; i < PosterAllowedExtensions.Length; i++)
                {
                    if (ext.ToLower() == PosterAllowedExtensions[i])
                        return 1;
                }

                string[] TrailerAllowedExtensions = new string[] { ".flv", ".asf", ".avi", ".wmv", ".mp4", ".mov", ".3gp", ".m4v", ".3g2" };
                for (int i = 0; i < TrailerAllowedExtensions.Length; i++)
                {
                    if (ext.ToLower() == TrailerAllowedExtensions[i])
                        return 2;
                }

                return 0;
        }

        protected void MatchesGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    int winner = Int32.Parse(e.Row.Cells[4].Text);

                    if (winner == -1)
                        e.Row.Cells[4].Text = "Partido sin jugar";
                    if (winner == 0)
                        e.Row.Cells[4].Text = "Empate";
                    if (winner != -1 && winner != 0)
                    {
                        e.Row.Cells[4].Text = TsSystem.Instance.GetTeamWithoutIncludes(winner).Name;
                    }
                }
            }
            catch (Exception)
            {
                //TODO: Loggear
            }
        }

        protected void ComboBoxSports_SelectedIndexChanged(object sender, EventArgs e)
        {
            Sport selectedSport = TsSystem.Instance.GetSportWithTeams(Int32.Parse(ComboBoxSports.SelectedValue));

            GridViewPositions.DataSource = TsSystem.Instance.GetPositionTable(selectedSport);
            GridViewPositions.DataBind();
        }


    }
}